import Bridge from './core/bridge';
import { setGlobalCssVar, switchTheme, initTheme } from './utils/tools';
import EventBus from './utils/event-bus';
import { getTileIdFromUrl } from './utils/tools';
import './style/main.css'

class LaunchPodsSDK {
  constructor(options = {}) {
    this.options = options;
    this.env = 'production';
    this._widget = null;
    this._tile = null;
    this._tileId = null;
    this.events = new EventBus();
    this.isReady = false;
    this.login = null;
    this.request = null;
    this.bridge = Bridge;
    this.theme = 'light';
    this.init();
  }
  get widget() {
    return this._widget;
  }
  setWidget(widget) {
    this._widget = widget;
  }
  get tile() {
    return this._tile;
  }
  setTile(tile) {
    this._tile = tile;
  }
  init(options = {}) {
    if (this.isReady) {
      return;
    }
    window.addEventListener("message", (event) => {
      const { type, data, source } = event.data;
      if (source !== 'platform') return;
      if (type === "initData") {
        const { tile, theme } = data;
        this._tile = tile;
        switchTheme(theme);
        this.events.emit('widget:ready');
      } else if (type === 'themeChanged') {
        switchTheme(data?.theme);
      }
    });
    document.addEventListener('contextmenu', function (event) {
      event.preventDefault();
      Bridge.send('widget-context-menu', {
        menuItems: [],
        data: {
          x: event.clientX,
          y: event.clientY
        },
        options: {}
      })
    });
    document.addEventListener("mousemove", (e) => {
      const target = document.elementFromPoint(e.clientX, e.clientY);
      const interactive = isInteractive(target);
      if (!interactive) {
        Bridge.send('widget-mouse-move', { x: e.clientX, y: e.clientY });
        console.log('[LaunchPodsSDK] mouse move', e.clientX, e.clientY);
      }
    });
    this._tileId = getTileIdFromUrl(window.location.href);
    console.log('[LaunchPodsSDK] tileId', this._tileId, window.location.href);
    this.bridge.init(this._tileId);
    // initWidgetDrag();

    this.isReady = true;
    console.log('[LaunchPodsSDK] Initialized !', options);
  }
  destroy() {
    console.log('[LaunchPodsSDK] Destroyed');
    this.bridge.destroy();
    this.events.emit('widget:destroy');
  }
  send() {

  }
  toggleTheme(themeName) {
    let theme = null;
    if (!themeName) {
      theme = this.theme === 'light' ? 'dark' : 'light';
    } else {
      theme = themeName;
    }
    switchTheme(theme);
    this.theme = theme;
    this.bridge.send('setTheme', { theme });
  }
  showContextMenu(event, menuItems, options = {}) {
    this.bridge.send('widget-context-menu', {
      menuItems: menuItems,
      data: {
        x: event.clientX,
        y: event.clientY
      },
      options: options
    })
  }
}

const LaunchPods = new LaunchPodsSDK();

const initAfterDomReady = () => {
  initTheme();
}

// 自动挂载到 window 以供 script 引入
if (typeof window !== 'undefined') {
  if (document.readyState === 'complete') {
    // DOM 加载完毕，资源（图片/iframe）未加载完
    // console.log('[LaunchPodsSDK] DOM complete', LaunchPods);
  } else if (document.readyState === 'interactive') {
    // 所有资源，包括图片、iframe 加载完成
    // console.log('[LaunchPodsSDK] DOM interactive', LaunchPods);
    initAfterDomReady();
  } else {
    window.addEventListener('DOMContentLoaded', async () => {
      // DOM 加载完毕
      // console.log('[LaunchPodsSDK] DOM ContentLoaded', LaunchPods);
    });
  }
  window.LaunchPods = LaunchPods;
}

export default LaunchPods;

function isInteractive(el) {
  if (!el) return false;
  const tag = el.tagName.toLowerCase();
  if (["button", "input", "textarea", "select", "a"].includes(tag)) return true;
  if (el.isContentEditable) return true;
  if (el.classList.contains("no-drag")) return true;
  return false;
}